import { useEffect, useState } from 'react';
import { Table, Button, Input, Space, Tag, Modal, Form, message, Card } from 'antd';
import { SearchOutlined, PlusOutlined, DollarOutlined } from '@ant-design/icons';
import { getUsers } from '../api/users';
import { createTransaction } from '../api/transactions';
import dayjs from 'dayjs';

const Users = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [transactionModal, setTransactionModal] = useState({ visible: false, user: null, type: null });
  const [form] = Form.useForm();

  useEffect(() => {
    fetchUsers();
  }, [pagination.current, pagination.pageSize, searchText]);

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await getUsers({
        page: pagination.current,
        limit: pagination.pageSize,
        search: searchText
      });
      if (response.success) {
        setUsers(response.data.users);
        setPagination(prev => ({
          ...prev,
          total: response.data.pagination.total
        }));
      }
    } catch (error) {
      console.error('Fetch users error:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const handleTableChange = (newPagination) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize
    }));
  };

  const openTransactionModal = (user, type) => {
    setTransactionModal({ visible: true, user, type });
    form.resetFields();
  };

  const closeTransactionModal = () => {
    setTransactionModal({ visible: false, user: null, type: null });
    form.resetFields();
  };

  const handleTransaction = async (values) => {
    try {
      const response = await createTransaction({
        userId: transactionModal.user.id,
        type: transactionModal.type,
        amount: values.amount,
        description: values.description
      });
      if (response.success) {
        message.success(transactionModal.type === 'recharge' ? '充值成功' : '消费成功');
        closeTransactionModal();
        fetchUsers();
      }
    } catch (error) {
      console.error('Transaction error:', error);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      render: (balance) => `¥${parseFloat(balance).toFixed(2)}`
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => (
        <Tag color={role === 'admin' ? 'red' : 'blue'}>
          {role === 'admin' ? '管理员' : '顾客'}
        </Tag>
      )
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<PlusOutlined />}
            onClick={() => openTransactionModal(record, 'recharge')}
          >
            充值
          </Button>
          <Button
            type="link"
            size="small"
            icon={<DollarOutlined />}
            onClick={() => openTransactionModal(record, 'consume')}
          >
            消费
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card
        title="用户管理"
        extra={
          <Input.Search
            placeholder="搜索用户姓名或手机号"
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            style={{ width: 300 }}
          />
        }
      >
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Card>

      <Modal
        title={transactionModal.type === 'recharge' ? '充值' : '消费'}
        open={transactionModal.visible}
        onCancel={closeTransactionModal}
        footer={null}
      >
        <div style={{ marginBottom: 16 }}>
          <p><strong>用户：</strong>{transactionModal.user?.name}</p>
          <p><strong>当前余额：</strong>¥{parseFloat(transactionModal.user?.balance || 0).toFixed(2)}</p>
        </div>
        <Form form={form} onFinish={handleTransaction} layout="vertical">
          <Form.Item
            name="amount"
            label="金额"
            rules={[
              { required: true, message: '请输入金额' },
              { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式' }
            ]}
          >
            <Input prefix="¥" placeholder="请输入金额" />
          </Form.Item>
          <Form.Item name="description" label="备注">
            <Input.TextArea rows={3} placeholder="选填" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
              <Button onClick={closeTransactionModal}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Users;
